package com.fyx.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fyx.config.*;
import com.fyx.entity.*;
import com.fyx.mapper.*;
import com.fyx.service.IGameService;
import com.fyx.until.DateUtil;
import com.fyx.until.HttpUtil;
import com.fyx.until.JsonUtil;
import com.fyx.utils.RedisUtils;
import com.fyx.utils.SecurityUtils;
import com.fyx.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;


import org.apache.commons.codec.binary.Base64;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 方扬秀
 * @since 2020-12-22
 */
@Service
public class GameServiceImpl extends ServiceImpl<PhoneInfoMapper, PhoneInfo> implements IGameService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Resource(name = FourthMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate fourthMongoTemplate;

    @Resource(name = FiveMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate fiveMongoTemplate;

    @Autowired
    private SysDictDetailMapper sysDictDetailMapper;

    @Override
    public Map suggest(MessageEntity messageEntity, Pageable pageable) {
        Query query = new Query();
        query.skip((pageable.getPageNumber())*pageable.getPageSize());
        query.limit(pageable.getPageSize());
        Criteria criteria = new Criteria();
        if (messageEntity.getPid()!=null){
            criteria.and("pid").is(messageEntity.getPid());
        }

        if (messageEntity.getQTime()!=null){
            criteria.andOperator(Criteria.where("time").gte(messageEntity.getQTime().get(0).getTime()/1000).lte(messageEntity.getQTime().get(1).getTime()/1000));
        }

        query.addCriteria(criteria);
        query.with( Sort.by(Sort.Direction.DESC,new String[]{"time"}));
        List<MessageEntity> list = mongoTemplate.find(query, MessageEntity.class);
        long total = mongoTemplate.count(query, MessageEntity.class);

        Map map =new HashMap();
        map.put("list",list);
        map.put("total",total);
        return map;
    }

    @Override
    public Map marqueeList(String mar_title, Pageable pageable){
        Query query = new Query();
        query.skip((pageable.getPageNumber())*pageable.getPageSize());
        query.limit(pageable.getPageSize());
        Criteria criteria = new Criteria();
        criteria.and("give_up").is(0);
        if (!StringUtils.isEmpty(mar_title)){
            criteria.and("msg_title").is(mar_title);
        }
        query.addCriteria(criteria);
        query.with( Sort.by(Sort.Direction.DESC,new String[]{"msg_id"}));
        List<LampEntity> list = mongoTemplate.find(query, LampEntity.class);
        if(list.size()>0){
        for(LampEntity lampEntity:list){
            List<Timestamp> qTime = new ArrayList<>();
            qTime.add(new Timestamp( new Date((long)lampEntity.getBeginTime()*1000).getTime()));
            qTime.add(new Timestamp( new Date((long)lampEntity.getEndTime()*1000).getTime()));
            lampEntity.setMarqueeTime(qTime);
            lampEntity.setChannel(lampEntity.getChannel());
          }
        }
        long total = mongoTemplate.count(query, LampEntity.class);
        Map map =new HashMap();
        map.put("list",list);
        map.put("total",total);
        return map;
    }

    @Override
    public boolean addMarquee(LampEntity lampEntity){
        try {
           Query query= new Query();
           query.with( Sort.by(Sort.Direction.DESC,new String[]{"msg_id"}));
           LampEntity lampEntity1=mongoTemplate.findOne(query,LampEntity.class);
            lampEntity.setBeginTime(Long.valueOf( lampEntity.getMarqueeTime().get(0).getTime()/1000).intValue());
            lampEntity.setEndTime(Long.valueOf( lampEntity.getMarqueeTime().get(1).getTime()/1000).intValue());
            lampEntity.setGive_up(0);
            lampEntity.setCreate_time(Long.valueOf( new Date().getTime()/1000).intValue());
            lampEntity.setCreate_user(SecurityUtils.getCurrentUsername());
            lampEntity.setCreate_userId(SecurityUtils.getCurrentUserId().intValue());
            String[] str= lampEntity.getChannel().replace("]","").replace("[","").replace("\"","").split(",");
            for(int i=0;i<str.length;i++) {
                if(lampEntity1!=null){
                    lampEntity.setMsg_id(lampEntity1.getMsg_id()+(i+1));}
                else{
                    lampEntity.setMsg_id(1);
                }
                lampEntity.setChannel(str[i]);
                lampEntity.setId(null);
                fourthMongoTemplate.insert(lampEntity);
            }
            return true;
        }catch (Exception e){
            return false;
        }

    }

    @Override
    public boolean delMarquee(String  id){
        try {
            Update update=new Update();
            update.set("give_up",1);
            update.set("delPeo", SecurityUtils.getCurrentUserId());
            update.set("delT",(int) (new Date().getTime()/1000));
            fourthMongoTemplate.updateFirst(new Query(Criteria.where("_id").is(id)),update,LampEntity.class);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    @Override
    public boolean toMarqueeNotice(String  id) throws IOException{
         JSONObject jsonObject = new JSONObject();
         jsonObject.put("id",id);
         JSONObject map = new JSONObject();
         map.put("cmd","toNotice_marquee");
         map.put("args",jsonObject);
         try {
             String result =HttpUtil.post(RequestConfig.baseRequestUrl, map.toJSONString(),"utf-8");
             JSONObject js= JSONObject.parseObject(result);
             if(js.getString("result").equals("true")){
                 return true;
             }else {
                 return false;
             }
         } catch (IOException e) {
             e.printStackTrace();
             return false;
         }
    }


    @Override
    public boolean editMarquee(LampEntity  lampEntity){
        try {
            Update update=new Update();
            update.set("msg_title",lampEntity.getMsg_title());
            update.set("msg",lampEntity.getMsg());
            update.set("num",lampEntity.getNum());
            update.set("currLive",lampEntity.getCurrLive());
            update.set("atOnce",lampEntity.getAtOnce());
            update.set("effects",lampEntity.getEffects());
            update.set("create_time",Long.valueOf( new Date().getTime()/1000).intValue());
            update.set("create_user",SecurityUtils.getCurrentUsername());
            update.set("create_userId",SecurityUtils.getCurrentUserId().intValue());
            update.set("beginTime",Long.valueOf( lampEntity.getMarqueeTime().get(0).getTime()/1000).intValue());
            update.set("endTime", Long.valueOf( lampEntity.getMarqueeTime().get(1).getTime()/1000).intValue());
            fourthMongoTemplate.updateFirst(new Query(Criteria.where("_id").is(lampEntity.getId())),update,LampEntity.class);
            return true;
        }catch (Exception e){
            return false;
        }

    }


    @Override
    public void sendEmail(CheckListEntity checkListEntity) {
        Update update = new Update();
        update.set("submit_time",(int) (new Date().getTime()/1000));
        update.set("submit_userId", SecurityUtils.getCurrentUserId());
        update.set("submit_userName",SecurityUtils.getCurrentUsername());
        update.set("status",1);
        fourthMongoTemplate.updateFirst(new Query(Criteria.where("_id").is(checkListEntity.get_id())),update,MessageEntity.class);

        CheckListEntity checkListEntity1 = new CheckListEntity();
        checkListEntity1.setStatus("0");
        checkListEntity1.setSubmit_reason(checkListEntity.getSubmit_reason());
        checkListEntity1.setCheck_reason(checkListEntity.getCheck_reason());
        checkListEntity1.setUserid(checkListEntity.getPid());
        checkListEntity1.setMail_type(checkListEntity.getMail_type());
        checkListEntity1.setMail_stype(checkListEntity.getMail_stype());
        checkListEntity1.setContent(checkListEntity.getContent());
        checkListEntity1.setTitle(checkListEntity.getTitle());

        QueryWrapper<SysDictDetail> wrapper=new QueryWrapper<>();
        wrapper.eq("dict_id",10);
        List<SysDictDetail> propsDictDictList =sysDictDetailMapper.selectList(wrapper);

        String awardsContent="";
        if(checkListEntity.getMail_stype()==3){
            checkListEntity1.setAwards(null);
            awardsContent=checkListEntity1.getContent();
        }else{
            List<AwardsEntity> awards =checkListEntity.getAwards();
            for(AwardsEntity awardsEntity:awards){
                String id =String.valueOf(awardsEntity.getId());
                String name="";
                String num = awardsEntity.getNum()+"";
                for(SysDictDetail SysDictDetail:propsDictDictList){
                    if(id.equals(SysDictDetail.getValue())){
                        name=SysDictDetail.getLabel();
                        awardsContent+=id+name+":"+num+",";
                    }
                }
            }
        }
        checkListEntity1.setAwardsContent(awardsContent);
        checkListEntity1.setSubmit_time((int) (new Date().getTime()/1000));
        checkListEntity1.setSubmit_userName(SecurityUtils.getCurrentUsername());
        checkListEntity1.setSubmit_userId(SecurityUtils.getCurrentUserId().toString());
        mongoTemplate.insert(checkListEntity1);
    }


    @Autowired
    private PhoneInfoMapper phoneInfoMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public Map phoneInfo(PhoneInfo phoneInfo, Pageable pageable) {
        Page<PhoneInfo> page = new Page<>(pageable.getPageNumber()+1,pageable.getPageSize());
        QueryWrapper<PhoneInfo> wrapper =new QueryWrapper<>();
        if(phoneInfo.getPhoneInfo()!=null){
            wrapper.like("phone_info",phoneInfo.getPhoneInfo());
        }
        IPage<PhoneInfo> ipage = null;
        if(redisUtils.hasKey("props_data")){
            ipage = phoneInfoMapper.selectPage(page,wrapper);
        }else{
            List<EtcEntity> list =mongoTemplate.find(new Query().addCriteria(new Criteria().and("name").is("phoneInfo")),EtcEntity.class);
            if(list.size()>0){
                Map map =list.get(0).getPhone_info();
                List<PhoneInfo> list1 = new ArrayList<>();
                for (Object key : map.keySet()) {
                    String mapKey = (String) key;
                    PhoneInfo phoneInfo1 = new PhoneInfo();
                    phoneInfo1.setPhoneInfo(mapKey);
                    list1.add(phoneInfo1);
                }
                phoneInfoMapper.delete(new QueryWrapper<>());
                phoneInfoMapper.insertBatch(list1);
                ipage = phoneInfoMapper.selectPage(page,wrapper);
                redisUtils.set("phone_info",ipage.getRecords(),600);
            }
        }
        List<PhoneInfo> phoneInfolist = ipage.getRecords();
        long total = ipage.getTotal();
        Map map =new HashMap();
        map.put("list",phoneInfolist);
        map.put("total",total);
        return map;
    }

    @Override
    public Map cdkCode(CdkDataEntity cdkDataEntity, Pageable pageable) {
        Query query = new Query();
        query.skip((pageable.getPageNumber())*pageable.getPageSize());
        query.limit(pageable.getPageSize());
        Criteria criteria = new Criteria();
        if(cdkDataEntity.getId()!=null){
            criteria.and("id").is(cdkDataEntity.getId());
        }
        if(cdkDataEntity.getGetted_num()!=null){
            criteria.and("getted_num").is(cdkDataEntity.getGetted_num());
        }
        query.addCriteria(criteria);
        query.with( Sort.by(Sort.Direction.DESC,new String[]{"create_time","getted_num"}));

        List<CdkDataEntity> list; long total=0;
        if(cdkDataEntity.getChannel()!=null&&cdkDataEntity.getChannel().equals("clmj")){
            list = fiveMongoTemplate.find(query, CdkDataEntity.class);
            total = fiveMongoTemplate.count(query, CdkDataEntity.class);
        }else {
            list = mongoTemplate.find(query, CdkDataEntity.class);
            total = mongoTemplate.count(query, CdkDataEntity.class);
        }
        Map map =new HashMap();
        map.put("list",list);
        map.put("total",total);
        return map;
    }

    @Override
    public void addCdkCode(CdkDataEntity cdkDataEntity) {
        String str1="",str2="";
       String[] str= cdkDataEntity.getChannel().replace("]","").replace("[","").replace("\"","").split(",");
       for(int i=0;i<str.length;i++){
           if(str[i].indexOf("cl_")>0||str[i].equals("totalcl")){
               if(str[i].equals("totalcl")){
                   str2 +=  "total,";
               }else {
                   str2 += str[i] + ",";
               }
           }else{
               str1 +=str[i]+",";
           }
       }
       String[] arr1=str1.split(",");
       String[] arr2=str2.split(",");
       if(!arr1[0].equals("")){
           Thread t = new Thread(new Runnable() {
               public void run() {
                   //     for(int i=0;i<str.length;i++) {
                   JSONObject jsonObject = new JSONObject();
                   jsonObject.put("channel", arr1);
                   jsonObject.put("head", cdkDataEntity.getHead());
                   jsonObject.put("award", cdkDataEntity.getAwards());
                   jsonObject.put("num", cdkDataEntity.getNum());
                   jsonObject.put("receive_limit", cdkDataEntity.getReceive_limit());
                   jsonObject.put("get_num", cdkDataEntity.getGet_num());
                   jsonObject.put("start_time", cdkDataEntity.getQTime().get(0).getTime() / 1000);
                   jsonObject.put("expire_time", cdkDataEntity.getQTime().get(1).getTime() / 1000);
                   jsonObject.put("need_rand", cdkDataEntity.isNeed_rand());
                   JSONObject map = new JSONObject();
                   map.put("cmd", "generate_cdk");
                   map.put("args", jsonObject);
                   try {
                       String result = HttpUtil.post(RequestConfig.baseRequestUrl, map.toJSONString(), "utf-8");
                   } catch (IOException e) {
                       e.printStackTrace();
                   }
               }
           });
           t.start();
       }
        if(!arr2[0].equals("")) {
            Thread  t = new Thread(new Runnable() {
                public void run() {
                    //     for(int i=0;i<str.length;i++) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("channel", arr2);
                    jsonObject.put("head", cdkDataEntity.getHead());
                    jsonObject.put("award", cdkDataEntity.getAwards());
                    jsonObject.put("num", cdkDataEntity.getNum());
                    jsonObject.put("receive_limit", cdkDataEntity.getReceive_limit());
                    jsonObject.put("get_num", cdkDataEntity.getGet_num());
                    jsonObject.put("start_time", cdkDataEntity.getQTime().get(0).getTime() / 1000);
                    jsonObject.put("expire_time", cdkDataEntity.getQTime().get(1).getTime() / 1000);
                    jsonObject.put("need_rand", cdkDataEntity.isNeed_rand());
                    JSONObject map = new JSONObject();
                    map.put("cmd", "generate_cdk");
                    map.put("args", jsonObject);
                    try {
                        String result = HttpUtil.post(RequestConfig.baseRequestUrl2, map.toJSONString(), "utf-8");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            t.start();
        }
    }

    @Override
    public Map advertising(AdvertisingEntity advertisingEntity, Pageable pageable) {
        Query query = new Query();
        query.skip((pageable.getPageNumber())*pageable.getPageSize());
        query.limit(pageable.getPageSize());
        Criteria criteria = new Criteria();
        if (advertisingEntity.getQTime()!=null){
            criteria.andOperator(Criteria.where("time").gte(advertisingEntity.getQTime().get(0).getTime()/1000).lte(advertisingEntity.getQTime().get(1).getTime()/1000));
        }
        query.addCriteria(criteria);
        query.with( Sort.by(Sort.Direction.DESC,new String[]{"time"}));
        List<AdvertisingEntity> list = mongoTemplate.find(query, AdvertisingEntity.class);
        long total = mongoTemplate.count(query, AdvertisingEntity.class);
        Map map =new HashMap();
        map.put("list",list);
        map.put("total",total);
        return map;
    }

    @Autowired
    private BasisDataMapper basisDataMapper;

    @Override
    public Map basisData(BasisData basisData, Pageable pageable) {
        Page<BasisData> page = new Page<>(pageable.getPageNumber()+1,pageable.getPageSize());
        QueryWrapper<BasisData> wrapper =new QueryWrapper<>();
        if(basisData.getQTime()!=null){
            wrapper.ge("time",basisData.getQTime().get(0).getTime()/1000);
            wrapper.le("time",basisData.getQTime().get(1).getTime()/1000);
        }
        wrapper.orderBy(true,false,"time");
        IPage<BasisData> ipage = basisDataMapper.selectPage(page,wrapper);
        List<BasisData> list = ipage.getRecords();
        long total = ipage.getTotal();
        Map map =new HashMap();
        map.put("list",list);
        map.put("total",total);
        return map;
    }

    @Autowired
    private RegisterDaysMapper registerDaysMapper;

    @Override
    public Map registerDays(RegisterDays registerDays,Pageable pageable) {
        Page<RegisterDays> page = new Page<>(pageable.getPageNumber()+1,pageable.getPageSize());
        QueryWrapper<RegisterDays> wrapper =new QueryWrapper<>();
        if(registerDays.getQTime()!=null){
            wrapper.ge("add_time",registerDays.getQTime().get(0).getTime()/1000);
            wrapper.le("add_time",registerDays.getQTime().get(1).getTime()/1000);
        }
        wrapper.orderBy(true,false,"add_time");
        IPage<RegisterDays> ipage = registerDaysMapper.selectPage(page,wrapper);
        List<RegisterDays> list = ipage.getRecords();
        long total = ipage.getTotal();
        Map map =new HashMap();
        map.put("list",list);
        map.put("total",total);
        return map;
    }

    @Resource(name = TertiaryMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate tertiaryMongoTemplate;

    @Resource(name = SeventhMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate seventhMongoTemplate;

    @Override
   public Map abilityList(String channel,Pageable pageable){

        Criteria criteria=new Criteria();
        criteria.and("name").is("功能开关");
        ActivityListEntity activityListEntity;
        if(channel.equals("totalcl")){
            activityListEntity=seventhMongoTemplate.findOne(new Query().addCriteria(criteria),ActivityListEntity.class);
        }else {
            activityListEntity=tertiaryMongoTemplate.findOne(new Query().addCriteria(criteria),ActivityListEntity.class);
        }
        JSONObject jsonObject =JSONObject.parseObject(activityListEntity.getConfigstr());
        QueryWrapper<SysDictDetail> wrapper=new QueryWrapper<>();
        wrapper.eq("dict_id",29);
        List<SysDictDetail> list=sysDictDetailMapper.selectList(wrapper);
        List list1 =new ArrayList();
        List list2 =new ArrayList();
        AbilityEntity abilityEntity=new AbilityEntity();
        if(list.size()>0){
            for (SysDictDetail sysDictDetail:list){
                try {
                        Map map = (Map)jsonObject.get(sysDictDetail.getValue());
                        abilityEntity=new AbilityEntity();
                        abilityEntity.setFlag(1);
                        abilityEntity.setName(sysDictDetail.getValue());
                        if(map.get("channelclose")!=null) {
                            abilityEntity.setChannelclose(map.get("channelclose").toString().substring(1).replaceAll("\"", "").replaceAll("]", "").split(","));
                        }if(map.get("channelopen")!=null) {
                            abilityEntity.setChannelopen(map.get("channelopen").toString().substring(1).replaceAll("\"", "").replaceAll("]", "").split(","));
                        }
                        abilityEntity.setOpen((Boolean) map.get("open"));
                        list1.add(abilityEntity);

                }catch (Exception e){
                    if(jsonObject.get(sysDictDetail.getValue())!=null) {
                        String[] all = jsonObject.get(sysDictDetail.getValue()).toString().substring(1).replaceAll("\"", "").replaceAll("]", "").split(",");
                        String[] allN = {};
                        abilityEntity = new AbilityEntity();
                        abilityEntity.setFlag(2);
                        abilityEntity.setName(sysDictDetail.getValue());
                        abilityEntity.setChannelclose(allN);
                        abilityEntity.setChannelopen(all);
                        abilityEntity.setOpen(false);
                        list2.add(abilityEntity);
                    }else {
                        String[] all = {};
                        String[] allN = {};
                        abilityEntity = new AbilityEntity();
                        abilityEntity.setFlag(2);
                        abilityEntity.setName(sysDictDetail.getValue());
                        abilityEntity.setChannelclose(allN);
                        abilityEntity.setChannelopen(all);
                        abilityEntity.setOpen(false);
                        list2.add(abilityEntity);
                    }
                }
            }
        }

        list1.addAll(list2);
        Map map =new HashMap();
        map.put("list",list1);
        map.put("total",20);
        return map;
    }



    @Override
    public Map appAbilityList(Pageable pageable){
        Criteria criteria=new Criteria();
        criteria.and("name").is("APP功能开关");
        ActivityListEntity activityListEntity=tertiaryMongoTemplate.findOne(new Query().addCriteria(criteria),ActivityListEntity.class);
        JSONObject jsonObject =JSONObject.parseObject(activityListEntity.getConfigstr());
        QueryWrapper<SysDictDetail> wrapper=new QueryWrapper<>();
        wrapper.eq("dict_id",29);
        List<SysDictDetail> list=sysDictDetailMapper.selectList(wrapper);
        List list1 =new ArrayList();
        AbilityEntity abilityEntity=new AbilityEntity();
        if(list.size()>0){
            for (SysDictDetail sysDictDetail:list){
                    Map map = (Map)jsonObject.get(sysDictDetail.getValue());
                    abilityEntity=new AbilityEntity();
                    abilityEntity.setName(sysDictDetail.getValue());
                    if(map!=null) {
                        if (map.get("channel") != null) {
                            abilityEntity.setChannelopen(map.get("channel").toString().substring(1).replaceAll("\"", "").replaceAll("]", "").split(","));
                        }
                        abilityEntity.setOpen((Boolean) map.get("open"));
                    }else {
                        String[] str= {};
                        abilityEntity.setChannelopen(str);
                        abilityEntity.setOpen(false);
                    }
                    list1.add(abilityEntity);
            }
        }
        System.out.println(list1);
        Map map =new HashMap();
        map.put("list",list1);
        map.put("total",20);
        return map;
    }

    @Override
    public boolean editAppAbility(AbilityEntity abilityEntity){
        Criteria criteria=new Criteria();
        criteria.and("name").is("APP功能开关");
        ActivityListEntity activityListEntity=tertiaryMongoTemplate.findOne(new Query().addCriteria(criteria),ActivityListEntity.class);
        JSONObject jsonObject =JSONObject.parseObject(activityListEntity.getConfigstr());
        QueryWrapper<SysDictDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_id", 30);
        List<SysDictDetail> list = sysDictDetailMapper.selectList(wrapper);
      //  String[] str = new String[list.size() - abilityEntity.getChannelopen().length];
//        if (str.length > 0) {
//            int i = 0;
//            for (SysDictDetail sysDictDetail : list) {
//                if (!Arrays.asList(abilityEntity.getChannelopen()).contains(sysDictDetail.getLabel())) {
//                    str[i] = sysDictDetail.getLabel();
//                    i++;
//                }
//            }
//        }
       // abilityEntity.setChannelcloe(str);
        Map map = new HashMap();
        map.put("open", abilityEntity.getOpen());
        map.put("channel", abilityEntity.getChannelopen());
        jsonObject.put(abilityEntity.getName(),map);
        System.out.println(jsonObject.toString());
        Update update=new Update();
        update.set("configstr",jsonObject.toString());
        System.out.println(jsonObject.toJSONString());
        tertiaryMongoTemplate.updateFirst(new Query().addCriteria(criteria),update,ActivityListEntity.class);
        return true;
    }

    @Override
    public boolean editAbility(AbilityEntity abilityEntity){
        System.out.println(abilityEntity);
        Criteria criteria=new Criteria();
        criteria.and("name").is("功能开关");
        ActivityListEntity activityListEntity=tertiaryMongoTemplate.findOne(new Query().addCriteria(criteria),ActivityListEntity.class);
        if(abilityEntity.getChannel().equals("totalcl")){
            activityListEntity=seventhMongoTemplate.findOne(new Query().addCriteria(criteria),ActivityListEntity.class);
        }
        JSONObject jsonObject =JSONObject.parseObject(activityListEntity.getConfigstr());
      //  Object res=jsonObject.get(abilityEntity.getName());
        if(abilityEntity.getFlag()==1) {
            QueryWrapper<SysDictDetail> wrapper = new QueryWrapper<>();

            if(abilityEntity.getChannel().equals("totalcl")){
                wrapper.eq("dict_id", 35);
            }
            else {
                wrapper.eq("dict_id", 30);
            }

            List<SysDictDetail> list = sysDictDetailMapper.selectList(wrapper);
            String[] str = new String[list.size() - abilityEntity.getChannelopen().length];
            if (str.length > 0) {
                int i = 0;
                for (SysDictDetail sysDictDetail : list) {
                    if (!Arrays.asList(abilityEntity.getChannelopen()).contains(sysDictDetail.getLabel())) {
                        str[i] = sysDictDetail.getLabel();
                        i++;
                    }
                }
            }
            abilityEntity.setChannelclose(str);
            Map map = new HashMap();
            map.put("open", abilityEntity.getOpen());
            map.put("channelclose", abilityEntity.getChannelclose());
            map.put("channelopen", abilityEntity.getChannelopen());
            jsonObject.put(abilityEntity.getName(),map);
        }else if(abilityEntity.getFlag()==2){
            jsonObject.put(abilityEntity.getName(),abilityEntity.getChannelopen());
        }
        Update update=new Update();
        update.set("configstr",jsonObject.toString());
        System.out.println(jsonObject.toJSONString());
        if(abilityEntity.getChannel().equals("totalcl")){
            seventhMongoTemplate.updateFirst(new Query().addCriteria(criteria),update,ActivityListEntity.class);
        }else{
            tertiaryMongoTemplate.updateFirst(new Query().addCriteria(criteria),update,ActivityListEntity.class);
        }
        return true;
    }

   @Autowired
   private MiniGameInfoMapper miniGameInfoMapper;

   @Override
   public List<MiniGameInfoEntity> getMiniGameList(){
       QueryWrapper<MiniGameInfoEntity> wrapper =new QueryWrapper<>();
       return  miniGameInfoMapper.selectList(wrapper);
   }

    @Override
   public Map miniGameList(MiniGameInfoEntity  miniGameInfoEntity, Pageable pageable){
       Page<MiniGameInfoEntity> page = new Page<>(pageable.getPageNumber()+1,pageable.getPageSize());
       QueryWrapper<MiniGameInfoEntity> wrapper =new QueryWrapper<>();
       wrapper.orderBy(true,false,"id");
       if(miniGameInfoEntity.getGameName()!=null){
           wrapper.eq("game_name",miniGameInfoEntity.getGameName());
       }
       IPage<MiniGameInfoEntity> ipage = miniGameInfoMapper.selectPage(page,wrapper);
       List<MiniGameInfoEntity> list = ipage.getRecords();
       long total = ipage.getTotal();
       Map map =new HashMap();
       map.put("list",list);
       map.put("total",total);
       return map;
   }
    @Override
    public boolean addMiniGame(MiniGameInfoEntity  miniGameInfoEntity){
      try{
          miniGameInfoEntity.setCreateId(SecurityUtils.getCurrentUserId().intValue());
          miniGameInfoEntity.setCreateTime(Integer.parseInt(new Date().getTime()/1000+"") );
          miniGameInfoMapper.insert(miniGameInfoEntity);
        return true;}
      catch (Exception e){
          return false;
      }
    }
    @Override
    public void delMiniGame(String id){
        miniGameInfoMapper.deleteById(id);
    }
    @Override
    public boolean editMiniGame(MiniGameInfoEntity  miniGameInfoEntity){
        try{
            miniGameInfoEntity.setUpdateId(SecurityUtils.getCurrentUserId().intValue());
            miniGameInfoEntity.setUpdateTime(Integer.parseInt(new Date().getTime()/1000+"") );
            miniGameInfoMapper.updateById(miniGameInfoEntity);
            return true;}
        catch (Exception e){
            return false;
        }
    }


    @Override
    public Map serverConfigList(ServerConfEntity  serverConfEntity, Pageable pageable){
        Query query = new Query();
        query.skip((pageable.getPageNumber())*pageable.getPageSize());
        query.limit(pageable.getPageSize());
        Criteria criteria = new Criteria();
        criteria.orOperator(Criteria.where("name").is("gated"),Criteria.where("name").is("tcpgated"));
        query.addCriteria(criteria);
        query.with( Sort.by(Sort.Direction.DESC,new String[]{"name"}));
        List<ServerConfEntity> list = tertiaryMongoTemplate.find(query, ServerConfEntity.class);
        if(list.size()>0){
            for (ServerConfEntity serverConfEntity1:list){
              serverConfEntity1.setStr(serverConfEntity1.getInit_args().get("supportversion").toString());
            }
        }
        long total = tertiaryMongoTemplate.count(query, ServerConfEntity.class);
        System.out.println(list);
        Map map =new HashMap();
        map.put("list",list);
        map.put("total",total);
        return map;
    }

}
